<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card
                    class="box-card"
                    shadow="never"
                >
                    <div
                        slot="header"
                        class="clearfix"
                    >
                        <span>网络状态&nbsp;&nbsp;IP:{{ipStr}}</span>
                    </div>
                    <el-row>
                        <el-col
                            id="intranetGauge"
                            style="width: 240px; height: 300px"
                        >
                        </el-col>
                        <el-col
                            id="internetGauge"
                            style="float: right; width: 240px; height: 300px"
                        >
                        </el-col>
                    </el-row>
                    <el-row
                        style="margin-top: 10px"
                        justify="space-between"
                    >
                        <el-row justify="space-between">
                            <el-col
                                :span="5"
                                :offset="3"
                            >
                                <el-button
                                    size="mini"
                                    type="primary"
                                    @click="randomIntranetSpeed"
                                >
                                    {{intranetButtonState}}
                                </el-button>
                            </el-col>
                            <el-col
                                :span="5"
                                :offset="9"
                            >
                                <el-button
                                    size="mini"
                                    type="primary"
                                    @click="internetSpeedTest"
                                >
                                    {{internetButtonState}}
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card
                    class="box-card"
                    shadow="never"
                >
                    <div
                        slot="header"
                        class="clearfix"
                    >
                        <span>存储信息&nbsp;&nbsp;IP:{{ipStr}}</span>
                    </div>
                    <el-row>
                        <el-col
                            id="localhostPie"
                            style="float: left; width: 240px; height: 300px"
                        >
                        </el-col>
                        <el-col
                            id="internetPie"
                            style="float: right; width: 240px; height: 300px"
                        >
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col
                            :span="6"
                            :offset="3"
                        >
                            总量: {{internetTotal}}GB
                        </el-col>
                        <el-col
                            :span="6"
                            :offset="8"
                        >
                            总量: {{localDiskTotal}}TB
                        </el-col>
                    </el-row>
                    <!-- <el-row style="margin-top: 10px">
                        <el-col
                            :span="7"
                            :offset="3"
                        >
                            预计可使用天数: {{formatDays(internetExpected)}}天
                        </el-col>
                        <el-col
                            :span="7"
                            :offset="7"
                        >
                            {{localDiskExpected}}
                        </el-col>
                    </el-row> -->
                </el-card>
            </el-col>
        </el-row>
        <el-row
            :gutter="20"
            style="margin-top: 20px"
        >
            <el-col :span="12">
                <el-card
                    class="box-card"
                    shadow="never"
                >
                    <div
                        slot="header"
                        class="clearfix"
                    >
                        <span>CPU使用率&nbsp;&nbsp;IP:{{ipStr}}</span>
                    </div>
                    <el-row>
                        <el-col
                            id="CPUusedrateLine"
                            class="custom-width"
                        >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card
                    class="box-card"
                    shadow="never"
                >
                    <div
                        slot="header"
                        class="clearfix"
                    >
                        <span>内存使用率&nbsp;&nbsp;IP:{{ipStr}}</span>
                    </div>
                    <el-row>
                        <el-col
                            id="RAMusedrateLine"
                            class="custom-width"
                        >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
const echarts = require('echarts');

const intranetGaugesetOption = function (myChart) {
    this.optionDP = {
        // 标题
        title: {
            text: '以太网网卡',
            left: '35%',
        },
        // 提示框
        tooltip: {
            formatter: '{b} : {c}',
        },
        // 刻度标签
        axisLabel: {
            color: '#888a8c',
            fontSize: 10,
            // 数据输出指定格式化
            formatter(v) {
                switch (`${v}`) {
                    case '0':
                        return v;
                    case '6':
                        return v;
                    case '12':
                        return v;
                    default:
                        return 0;
                }
            },
        },
        series: [
            {
                min: 0,
                max: 12,
                color: '#ff0000',
                // 刻度样式
                axisTick: {
                    show: false,
                },
                // 仪表盘轴线样式
                axisLine: {
                    lineStyle: {
                        color: [
                            [this.intranetSpeed.split(' ')[0] / 12, '#2586ee'],
                            [1, '#888a8c'],
                        ],
                        width: 5,
                    },
                },
                // 分隔线样式
                splitLine: {
                    length: 20,
                    lineStyle: {
                        color: '#2586ee',
                        width: 5,
                    },
                },
                // 指针
                pointer: {
                    length: '100%',
                    width: 4,
                    itemStyle: {},
                },
                title: {
                    name: '当前网速',
                    left: '30%',
                },
                splitNumber: 6,
                type: 'gauge',
                // 仪表盘数据
                detail: {
                    formatter: `{value}${this.intranetSpeed.split(' ')[1]}`,
                    textStyle: {
                        color: '#ff0000',
                    },
                },
                data: [
                    {
                        value: this.intranetSpeed.split(' ')[0],
                        name: '当前网速',
                    },
                ],
            },
        ],
    };
    myChart.resize();
    myChart.setOption(this.optionDP);
};
const internetGaugesetOption = function (myChart) {
    this.optionDP = {
        title: {
            text: '互联网网卡',
            left: '35%',
        },
        tooltip: {
            formatter: '{b} : {c}',
        },
        axisLabel: {
            color: '#888a8c',
            fontSize: 10,
            formatter(v) {
                switch (`${v}`) {
                    case '0':
                        return v;
                    case '6':
                        return v;
                    case '12':
                        return v;
                    default:
                        return 0;
                }
            },
        },
        series: [
            {
                min: 0,
                max: 12,
                color: '#ff0000',
                axisTick: {
                    show: false,
                },
                axisLine: {
                    // show: false,
                    lineStyle: {
                        color: [
                            [this.internetSpeed.split(' ')[0] / 12, '#2586ee'],
                            [1, '#888a8c'],
                        ],
                        width: 5,
                    },
                },
                splitLine: {
                    length: 20,
                    lineStyle: {
                        color: '#2586ee',
                        width: 5,
                    },
                },
                pointer: {
                    length: '100%',
                    width: 4,
                },
                title: {
                    name: '当前网速',
                },
                type: 'gauge',
                splitNumber: '6',
                // show: false,
                detail: {
                    formatter: `{value}${this.internetSpeed.split(' ')[1]}`,
                    textStyle: {
                        color: '#ff0000',
                    },
                },
                data: [
                    {
                        value: this.internetSpeed.split(' ')[0],
                        name: '当前网速',
                    },
                ],
            },
        ],
    };
    myChart.resize();
    myChart.setOption(this.optionDP);
};
const localhostPieOption = function (myChart) {
    this.optionDP = {
        title: {
            text: '本机存储',
            x: 'center',
        },
        tooltip: {
            trigger: 'item',
            formatter: '{c}T ({d}%)',
        },
        legend: {
            orient: 'vertical',
            x: 'left',
            data: ['使用量', '剩余量'],
        },
        series: [
            {
                name: '存储量',
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: [
                    {
                        value: this.localDiskUsed,
                        name: '使用量',
                    },
                    {
                        value: this.localDiskFree,
                        name: '剩余量',
                    },
                ],
                label: {
                    // formatter: "{b}:{c}G",
                    normal: {
                        show: false,
                        position: 'center',
                    },
                },
                labelLine: {
                    normal: {
                        show: false,
                    },
                },

                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                    },
                },
            },
        ],
    };
    myChart.resize();
    myChart.setOption(this.optionDP);
};
const internetPieOption = function (myChart) {
    this.optionDP = {
        title: {
            text: '内存存储',
            x: 'center',
        },
        tooltip: {
            trigger: 'item',
            formatter: '{c}G ({d}%)',
        },
        legend: {
            orient: 'vertical',
            x: 'left',
            data: ['使用量', '剩余量'],
        },
        series: [
            {
                name: '存储量',
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: [
                    {
                        value: this.internetUsed,
                        name: '使用量',
                    },
                    {
                        value: this.internetFree,
                        name: '剩余量',
                    },
                ],
                label: {
                    // formatter: "{b}:{c}G",
                    normal: {
                        show: false,
                        position: 'center',
                    },
                },
                labelLine: {
                    normal: {
                        show: false,
                    },
                },
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                    },
                },
            },
        ],
    };
    myChart.resize();
    myChart.setOption(this.optionDP);
};

const CPUusedrateLineOption = function (myChart) {
    this.optionDP = {
        tooltip: {
            trigger: 'axis',
            formatter: '{b} {a}:{c}%',
        },
        xAxis: {
            name: '时间',
            type: 'category',
            boundaryGap: false,
            data: this.systemInfoFormatDate,
        },
        yAxis: {
            name: '使用率(%)',
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
                show: false,
            },
        },
        series: [
            {
                name: 'CPU使用率',
                type: 'line',
                hoverAnimation: false,
                data: this.cpuUsedPercent.reverse(),
                smooth: true,
            },
        ],
    };
    myChart.resize();
    myChart.setOption(this.optionDP);
};
const RAMusedrateLineOption = function (myChart) {
    this.optionDP = {
        tooltip: {
            trigger: 'axis',
            formatter: '{b} {a}:{c}%',
        },
        xAxis: {
            name: '时间',
            type: 'category',
            boundaryGap: false,
            data: this.systemInfoFormatDate,
        },
        yAxis: {
            name: '使用率(%)',
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
                show: false,
            },
        },
        series: [
            {
                name: '内存使用率',
                type: 'line',
                showSymbol: false,
                hoverAnimation: false,
                data: this.memUsedPercent.reverse(),
            },
        ],
    };
    myChart.resize();
    myChart.setOption(this.optionDP);
};

export default {
    name: 'DiagnosisScanMonitoring',
    data() {
        return {
            systemInfo: {
                memoryTotalOfG: 0,
                memoryUsedOfG: 0,
                memoryFreeOfG: 0,
                diskTotalOfT: 0,
                diskUsedOfT: 0,
                diskFreeOfT: 0,
            },
            systemInfoDate: [],
            cpuUsedPercent: [],
            memUsedPercent: [],
            intranetButtonState: '网速测试',
            internetButtonState: '网速测试',
            localDiskExpectedFromServer: '',
            ipStr: '未知IP',
        };
    },
    mounted() {
        this.intranetGaugesetOptionReset();
        this.internetGaugesetOptionReset();
        // this.localhostPieOptionReset();

        // this.CPUusedrateLineOptionReset();
        // this.RAMusedrateLineOptionReset();
        this.getDiskWithMemory();
        this.systemInfoRequest();
        this.getRestDays();
    },
    computed: {
        intranetSpeed() {
            return '0 Kbps';
        },
        internetSpeed() {
            return '0 Kbps';
        },
        localDiskUsed() {
            return this.systemInfo.diskUsedOfT;
        },
        localDiskFree() {
            return this.systemInfo.diskFreeOfT;
        },
        localDiskTotal() {
            if (this.systemInfo.diskTotalOfT) {
                return this.systemInfo.diskTotalOfT;
            }
            return 0;
        },
        localDiskExpected() {
            return this.localDiskExpectedFromServer;
        },
        internetUsed() {
            return this.systemInfo.memoryUsedOfG;
        },
        internetFree() {
            return this.systemInfo.memoryFreeOfG;
        },
        internetTotal() {
            return this.systemInfo.memoryTotalOfG;
        },
        internetExpected() {
            return 0;
        },
        systemInfoFormatDate() {
            return this.systemInfoDate;
        },
    },
    methods: {
        intranetGaugesetOptionReset() {
            const applicationintranetGauge = echarts.init(
                document.getElementById('intranetGauge')
            );
            intranetGaugesetOption.call(this, applicationintranetGauge);
        },
        internetGaugesetOptionReset() {
            const applicationinternetGauge = echarts.init(
                document.getElementById('internetGauge')
            );
            internetGaugesetOption.call(this, applicationinternetGauge);
        },
        localhostPieOptionReset() {
            const applicationlocalhostPie = echarts.init(
                document.getElementById('internetPie')
            );
            localhostPieOption.call(this, applicationlocalhostPie);
        },
        internetPieOptionReset() {
            const applicationinternetPie = echarts.init(
                document.getElementById('localhostPie')
            );
            internetPieOption.call(this, applicationinternetPie);
        },
        CPUusedrateLineOptionReset() {
            const applicationCPUusedrateLine = echarts.init(
                document.getElementById('CPUusedrateLine')
            );
            CPUusedrateLineOption.call(this, applicationCPUusedrateLine);
        },
        RAMusedrateLineOptionReset() {
            const applicationRAMusedrateLine = echarts.init(
                document.getElementById('RAMusedrateLine')
            );
            RAMusedrateLineOption.call(this, applicationRAMusedrateLine);
        },
        formatBytes1(bytes, decimals = 2) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
        },
        formatDays(days) {
            if (days > 1000) {
                return '>1000';
            }
            return days;
        },
        formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return '0 bps';

            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = [
                'bps',
                'Kbps',
                'Mbps',
                'Gbps',
                'Tbps',
                'Pbps',
                'Ebps',
                'Zbps',
                'Ybps',
            ];

            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
        },
        randomIntranetSpeed() {
            const min = 8388608;
            const max = 10485760;
            const testData = Math.floor(Math.random() * (max - min)) + min;
            if (this.intranetButtonState === '网速测试') {
                this.intranetButtonState = '测试中...';
            }
            setTimeout(() => {
                // return this.formatBytes(Number(testData));
                const applicationintranetGauge = echarts.init(
                    document.getElementById('intranetGauge')
                );
                applicationintranetGauge.setOption({
                    series: [
                        {
                            // 仪表盘轴线样式
                            axisLine: {
                                lineStyle: {
                                    color: [
                                        [
                                            this.formatBytes(
                                                Number(testData)
                                            ).split(' ')[0] / 1024,
                                            '#2586ee',
                                        ],
                                        [1, '#888a8c'],
                                    ],
                                    width: 5,
                                },
                            },
                            detail: {
                                formatter: `{value}${
                                    this.formatBytes(Number(testData)).split(
                                        ' '
                                    )[1]
                                }`,
                                textStyle: {
                                    color: '#ff0000',
                                },
                            },
                            data: [
                                {
                                    value: this.formatBytes(
                                        Number(testData)
                                    ).split(' ')[0],
                                    name: '当前网速',
                                },
                            ],
                        },
                    ],
                });
                this.intranetButtonState = '网速测试';
            }, 5000);
        },
        internetSpeedTest() {
            if (this.internetButtonState === '网速测试') {
                this.internetButtonState = '测试中...';
            }

            this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/network-speed',
            }).then((res, err) => {
                if (res.data.code !== 200 || !res.data.data) {
                    throw new Error(err);
                }
                console.log('network', res);
                const data = (
                    parseFloat(res.data.data.speed) *
                    1024 *
                    1024
                ).toFixed(0);
                setTimeout(() => {
                    const applicationinternetGauge = echarts.init(
                        document.getElementById('internetGauge')
                    );
                    applicationinternetGauge.setOption({
                        series: [
                            {
                                // 仪表盘轴线样式
                                axisLine: {
                                    lineStyle: {
                                        color: [
                                            [
                                                this.formatBytes(
                                                    Number(data)
                                                ).split(' ')[0] / 1024,
                                                '#2586ee',
                                            ],
                                            [1, '#888a8c'],
                                        ],
                                        width: 5,
                                    },
                                },
                                detail: {
                                    formatter: `{value}${
                                        this.formatBytes(Number(data)).split(
                                            ' '
                                        )[1]
                                    }`,
                                    textStyle: {
                                        color: '#ff0000',
                                    },
                                },
                                data: [
                                    {
                                        value: this.formatBytes(
                                            Number(data)
                                        ).split(' ')[0],
                                        name: '当前网速',
                                    },
                                ],
                            },
                        ],
                    });
                    this.internetButtonState = '网速测试';
                }, 1000);
            });
        },
        async getDiskWithMemory() {
            await this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/system/getDiskWithMemory',
            }).then((res, err) => {
                if (res.data.code !== 200) {
                    throw new Error(err);
                }
                const result = res.data.data;
                if (result) {
                    Object.keys(this.systemInfo).forEach((key) => {
                        this.systemInfo[key] = result[key];
                    });
                }
            });
            // 刷新图表数据
            this.localhostPieOptionReset();
            this.internetPieOptionReset();
        },
        async systemInfoRequest() {
            try {
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/system/rencent',
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    const result = res.data.data;
                    if (result) {
                        this.systemInfoDate = [];
                        this.cpuUsedPercent = [];
                        this.memUsedPercent = [];
                        for (let i = 0; i < result.length; i++) {
                            this.systemInfoDate.unshift(
                                result[i].createTime.split(' ')[1]
                            );
                            this.cpuUsedPercent.push(result[i].cpuUsed);
                            this.memUsedPercent.push(
                                (
                                    (result[i].memUsed / result[i].memTotal) *
                                    100
                                ).toFixed(1)
                            );
                        }
                    }
                });
                // 刷新图表数据
                this.CPUusedrateLineOptionReset();
                this.RAMusedrateLineOptionReset();
            } catch (e) {
                throw new Error(e);
            }
        },
        async getRestDays() {
            try {
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/system/disk-available-days',
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    const result = res.data.data;
                    if (result) {
                        this.localDiskExpectedFromServer = result.days;
                        this.ipStr = result.ipStr;
                    }
                });
            } catch (e) {
                throw new Error(e);
            }
        },
    },
};
</script>

<style scoped>
.custom-width {
    width: 100%;
    height: 300px;
}
</style>
